import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/smoking_record.dart';
import '../services/storage_service.dart';
import 'calendar_page.dart';
import 'package:animations/animations.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final StorageService _storageService = StorageService();
  List<SmokingRecord> _todayRecords = [];
  
  @override
  void initState() {
    super.initState();
    _loadTodayRecords();
  }
  
  // 加载今天的记录
  Future<void> _loadTodayRecords() async {
    final records = await _storageService.getRecordsForDate(DateTime.now());
    setState(() {
      _todayRecords = records;
    });
  }
  
  // 记录一次吸烟
  Future<void> _recordSmoking() async {
    final record = SmokingRecord(timestamp: DateTime.now());
    await _storageService.addRecord(record);
    _loadTodayRecords();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('戒烟助手'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.calendar_month),
            onPressed: () {
              Navigator.of(context).push(
                PageRouteBuilder(
                  transitionDuration: const Duration(milliseconds: 500),
                  pageBuilder: (context, animation, secondaryAnimation) => const CalendarPage(),
                  transitionsBuilder: (context, animation, secondaryAnimation, child) {
                    return SharedAxisTransition(
                      animation: animation,
                      secondaryAnimation: secondaryAnimation,
                      transitionType: SharedAxisTransitionType.horizontal,
                      child: child,
                    );
                  },
                ),
              ).then((_) => _loadTodayRecords()); // 返回时刷新数据
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 今日统计
          Container(
            padding: const EdgeInsets.all(16.0),
            margin: const EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceVariant,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              children: [
                Text(
                  '今日 ${DateFormat('yyyy年MM月dd日').format(DateTime.now())}',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.smoking_rooms, color: Colors.red, size: 36),
                    const SizedBox(width: 16),
                    Text(
                      '已抽 ${_todayRecords.length} 根',
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          // 今日记录列表
          Expanded(
            child: _todayRecords.isEmpty
                ? const Center(
                    child: Text('今天还没有抽烟记录，继续保持！'),
                  )
                : ListView.builder(
                    itemCount: _todayRecords.length,
                    itemBuilder: (context, index) {
                      final record = _todayRecords[index];
                      return ListTile(
                        leading: const Icon(Icons.smoking_rooms, color: Colors.red),
                        title: Text('第 ${index + 1} 根'),
                        subtitle: Text('时间: ${record.getFormattedTime()}'),
                      );
                    },
                  ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () async {
          await showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) {
              return Dialog(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
                elevation: 8,
                backgroundColor: Colors.white,
                child: Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          gradient: LinearGradient(
                            colors: [Colors.red.shade400, Colors.orange.shade200],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.red.withOpacity(0.2),
                              blurRadius: 16,
                              offset: const Offset(0, 8),
                            ),
                          ],
                        ),
                        padding: const EdgeInsets.all(18),
                        child: const Icon(Icons.smoking_rooms, color: Colors.white, size: 48),
                      ),
                      const SizedBox(height: 20),
                      const Text(
                        '确认记录？',
                        style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Colors.black87),
                      ),
                      const SizedBox(height: 12),
                      Text(
                        '您今日已抽 ${_todayRecords.length} 根烟',
                        style: const TextStyle(fontSize: 18, color: Colors.black54),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        _todayRecords.length == 0
                          ? '继续保持无烟生活！'
                          : (_todayRecords.length < 5
                              ? '做得不错，继续努力！'
                              : '请注意健康，适量为宜'),
                        style: TextStyle(fontSize: 15, color: Colors.red.shade400, fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(height: 24),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          TextButton(
                            onPressed: () => Navigator.of(context).pop(),
                            style: TextButton.styleFrom(
                              foregroundColor: Colors.grey.shade700,
                              textStyle: const TextStyle(fontSize: 16),
                            ),
                            child: const Text('取消'),
                          ),
                          ElevatedButton(
                            onPressed: () async {
                              Navigator.of(context).pop();
                              await _recordSmoking();
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              foregroundColor: Colors.white,
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),
                              textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                              elevation: 2,
                            ),
                            child: const Text('确认记录'),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
        icon: const Icon(Icons.add),
        label: const Text('记录抽烟'),
        backgroundColor: Colors.red,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
} 